﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace eBrain
{
    public partial class Exp_VisualSearch : Experiment
    {


        public Exp_VisualSearch(TestControlWindow _tcw, ExperimentMainForm _expw)//, int _w, int _h)
            : base(_tcw, _expw)//, _w, _h) 
        {}

        public Exp_VisualSearch(ExperimentMainForm _expw, string datapath, string logpath, string sInputMode)
            : base(_expw, datapath, logpath, sInputMode)//, _w, _h) 
        { }

        public override void UpdateCanvas()
        {

            //int x, y, w, h, x0, y0, w1, h1;
            //string sx, sy;
            string imgfile = "";
            //string text = "";

            //ExperimentStatus old_status = exp_status;
            //exp_status = ExperimentStatus.UpdatingGraphics;

            //mtx.WaitOne();

            //lock (myCanvas)
            //{

                //bUpdatingCanvas = true;

                myExpW.LockCanvasUserCopy();
                Graphics CanvasGraphics = Graphics.FromImage(myExpW.CanvasUserCopy);
                CanvasGraphics.Clear(bkgrnd);

                //aggiorno lo sfondo
                if (bTrainingMode)
                    imgfile = TrainingTrials.Item(ActualTrialNumber).Attributes["Filename"].Value + ".bmp";
                else
                    imgfile = Trials.Item(ActualTrialNumber).Attributes["Filename"].Value + ".bmp";

                if (imgfile != "")
                {
                    Image myImag = Image.FromFile(sImagePath + imgfile);
                    CanvasGraphics.DrawImageUnscaled(myImag, 0, 0);
                }

                CanvasGraphics.Dispose();
                myExpW.CopyCanvas();
                
                myExpW.UnlockCanvasUserCopy();

            myExpW.Invalidate();

                //Le ROI non sono costanti. verifico in quale caso stiamo 
                UpdateVariableROIList();

                //exp_status = old_status;
                //mtx.ReleaseMutex();
                
            //}
        }


        /// <summary>
        /// GEstisco la selezione che è stata richiamata dal gestore di eventi
        /// </summary>
        public override void SelectionHandler()
        {
            //lo metto nella lista dei risultati
            //string s = myParam.KeySequence.Substring(key_typed, 1);
            String s = myROIList.myRoiList[ROI_Selected].sItem;
            int val = myROIList.myRoiList[ROI_Selected].iValue;

            myResultList.Add(new ResultListElement(val, s, ""));

            //NumOfLetters++;

            myLog.Log("Target selected: " + s);


            if (bUseSounds)
            {
                SPSelection.Play();
            }

            bROISelected = false;

            //resetto la roi selezionata
            ROI_Selected = RoiList.NO_ROI;


            //<DataViewer>
            if (bEyelinkConnected)
                ET.SendCommand("TRIAL_RESULT 0");


            if (bTrainingMode)
            {
                if (++ActualTrialNumber >= TrainingTrials.Count)
                    FromTrainingToTrials();
                else
                {

                    DoNextTrial();
                }

            }
            else
            {
                if (++ActualTrialNumber >= Trials.Count)
                {
                    ActualTrialNumber = Trials.Count - 1;
                    EndOfTrials = true;

                    EndOfTest();
                    //SaveResults();
                    //EndOfTest();
                }
                else
                {
                    //TODO: mettere a posto perchp qui non va benissimo - solo per prova
                    DoNextTrial();
                    //UpdateCanvas();
                    //this.Invalidate();
                }
            }
        }


        public override void UpdateVariableROIList()
        {
            int x, y, w, h;//x0, y0, , w1, h1;
            myROIList.myRoiList.Clear();

            if (!bConstantRois)
            {
                //non siamo nel caso di ROI omogenee (es. Visual Search). 
                //procedo a seconda del tipo di esperimento

                if (ExperimentType == _ExperimentType.VisualSearch)
                {
                    string ROIFileName;

                    if (bTrainingMode)
                        ROIFileName = TrainingTrials.Item(ActualTrialNumber).Attributes["Filename"].Value + ".xml";
                    else
                        ROIFileName = Trials.Item(ActualTrialNumber).Attributes["Filename"].Value + ".xml";

                    XmlDocument TrialDoc = new XmlDocument();
                    TrialDoc.Load(sImagePath + ROIFileName);

                    XmlNode MainTargetNode = TrialDoc.SelectSingleNode("Targets/MainTarget");

                    w = int.Parse(MainTargetNode.Attributes["MaxWidth"].Value);
                    h = int.Parse(MainTargetNode.Attributes["MaxHeight"].Value);

                    x = int.Parse(MainTargetNode.Attributes["x0"].Value) - w / 2;
                    y = int.Parse(MainTargetNode.Attributes["y0"].Value) - h / 2;

                    //Aggiungo il primo elemento (il target)
                    myROIList.AddElement(x, y, w, h, true, "", "T", 1);

                    XmlNodeList ConfounderList = TrialDoc.SelectNodes("Targets/ConfounderTargets/ConfounderTarget");

                    for (int k = 0; k < ConfounderList.Count; k++)
                    {
                        x = int.Parse(ConfounderList.Item(k).Attributes["x0"].Value) - w / 2;
                        y = int.Parse(ConfounderList.Item(k).Attributes["y0"].Value) - h / 2;

                        //Aggiungo gli altri elementi
                        myROIList.AddElement(x, y, w, h, true,"", "C", 0);

                    }
                }
            }
        }


    }

}
